<?php
namespace Home\Controller;

use Lib\Controller\HomeBaseController;
use Think\Upload;

//首页-控制器
class PersonalController extends HomeBaseController {
    public $userInfo;
    private $videoBookModel;
    private $videoBookInfoModel;
    private $provinceModel;
    private $cityModel;
    private $hospitalModel;
    public function __construct(){
        $this->videoBookModel   = D('VideoBook');       //预定订单
        $this->provinceModel    = D('Province');        //省份
        $this->cityModel        = D('City');       	    //城市
        $this->hospitalModel    = D('Hospital');        //医院
        $this->userInfo         = cookie('userinfo');
        $this->videoBookInfoModel = D('VideoBookInfo');
        parent::__construct();
    }
    /**
     * 订单列表页
     */
    public function my_baby_order(){
        $userInfo = $this->userInfo;
        $where['user_id'] = $userInfo['id'];
        $result = $this->videoBookModel->where($where)->order('id desc')->select();
        if($result){
            foreach($result as $key => $val){
                $result[$key]['provinceName'] = $this ->provinceModel ->field('ProvinceName')->where('ProvinceID = '.$val['provinceid'])->find();
                $result[$key]['cityName'] = $this ->cityModel ->field('CityName')->where('CityID = '.$val['cityid'])->find();
                $result[$key]['hospitalName'] = $this ->hospitalModel ->field('hospital_name')->where('id = '.$val['hospitalid'])->find();
            }
        }
        $this->assign('orderList',$result);
        $this->display();
    }

    /**
     * [compelete_infomation 完善信息页面展示]
     * @author xiezy
     * @date   2018-05-14
     * @return [type]     [description]
     */
    public function compelete_infomation(){
        $type = I('get.type');
        $where['ordersn'] = I('get.ordersn');

        $orderResult = $this->videoBookModel->where($where)->find();

        if($orderResult){
            $orderResult['hospital_info'] = $this->hospitalModel ->field('hospital_name')->where('id = '.$orderResult['hospitalid'])->find();
        }
        $orderInfoResult = $this->videoBookInfoModel->where($where)->find();
        for($i = 0;$i <= 19;$i++){
            if($orderInfoResult['video_material_img_'.$i] != null){
                // $delimgurl = 'upload/'.$orderInfoResult['video_material_img_'.$i];
                // unlink($delimgurl);
                // $orderInfoResult22222['video_material_img_'.$i] = '';
                // $this->videoBookInfoModel->where($where)->save($orderInfoResult22222);
                $arr[$i] = array($i=>$orderInfoResult['video_material_img_'.$i]);
            }
        }
        if(isset($arr)){
            foreach($arr as $key =>$val){
                foreach($val as $k => $v){
                    $orderInfoResult['img_arr'][$key] = $v;
                }
                $orderInfoResult['img_num'] = $key+1;
            }
        }else{
            $orderInfoResult['img_num'] = 0;
        }

        $this->assign('order',$orderResult);
        $this->assign('info',$orderInfoResult);
        $this->assign('type',$type);
        $this->display();
    }
    /**
     * 保存完善信息
     */
    public function save_order_info(){
        //订单号作为查询条件
        $where['ordersn'] = I('post.ordersn');

        //预约订单详情的内容
        $saveBookInfoDate = array(
            'bron_time'     => strtotime(I('post.bron_time')),
            'baby_weight'   => I('post.baby_weight'),
            'baby_height'   => I('post.baby_height'),
            'baby_sex'      => I('post.baby_sex'),
        );

        //保存操作
        $videoBookInfoSaveResult = $this->videoBookInfoModel->where($where)->save($saveBookInfoDate);

        if($videoBookInfoSaveResult!==false){
            $returndata['status'] = 1;
            $returndata['info'] = '保存成功';
            $returndata['url'] = U(MODULE_NAME.'/personal/my_baby_order');
            $this->ajaxReturn($returndata);
        }else{
            $returndata['status'] = 0;
            $returndata['info'] = '保存失败';
            $this->ajaxReturn($returndata);
        }
    }

    /**
     * [save_order_file 保存订单图片素材]
     * @author xiezy
     * @date   2018-05-21
     * @return [type]     [description]
     */
    public function save_order_file(){
        //当前图片数量（未包括当前添加数量）
        $c_img_num        = I('post.c_img_num');
        //订单号作为查询条件
        $where['ordersn'] = I('post.ordersn');

        if($_FILES['photo']['name'][0] != ''){
            //上传图片的配置
            $config = array(
                'maxSize' => 0, //上传的文件大小限制 (0-不做限制)
                'exts' => array('jpg', 'gif', 'png', 'jpeg'),// 设置附件上传类型
                'subName' => array('date', 'Ymd'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                // 'saveName'   => array('uniqid', array('', true)),
                'savePath' => C('UPLOAD_CAR_IMG_PATH'), //保存路径
                'rootPath' => './Upload/',
                'autoSub'    =>    true,
            );
            $this->uploader = new Upload($config, 'Local');
            $info = $this->uploader->upload($_FILES);
            // P($_FILES);
            if(!$info){//提示错误信息
                $returndata ['status'] = 0; // 状态
                $returndata ['info'] = $this->uploader->getError();
                $this->ajaxReturn($returndata);
            }else{
                foreach($info as$x =>$val){
                    $k = $x+$c_img_num;
                    $saveBookInfoImgDate['video_material_img_'.$k] = $val['savepath'] . $val['savename'];
                }
                // echo '<meta charset="UTF-8"><pre>xie '.date('Y-m-d H:i:s',time()).'</br></br>';var_dump($saveBookInfoImgDate);die;
                $uploadResult = $this->videoBookInfoModel->where($where)->save($saveBookInfoImgDate);
                if($uploadResult!==false){
                    $returndata['status'] = 1;
                    $returndata['info'] = '上传成功';
                    $this->ajaxReturn($returndata);
                }else{
                    $returndata['status'] = 0;
                    $returndata['info'] = '上传失败';
                    $this->ajaxReturn($returndata);
                }
            }
        }else{
                $returndata['status'] = 0;
                $returndata['info'] = '上传失败';
                $this->ajaxReturn($returndata);
        }
    }

    /**
     * [cancel_order 取消订单]
     * @author xiezy
     * @date   2018-05-14
     * @return [type]     [description]
     */
    public function cancel_order(){
        $where['ordersn'] = I('post.ordersn');
        $data['is_pay'] = '-1';

        $result = $this->videoBookModel->where($where) ->save($data);

        if($result){
            $info['status'] = 1;
            $info['info'] = '取消成功';
            $info['url'] = U(MODULE_NAME.'/personal/my_baby_order');
            $this->ajaxReturn($info);
        }else{
            $info['status'] = 0;
            $info['info'] = '取消失败';
            $this->ajaxReturn($info);
        }
    }

    /**
     * [showVideoOnline 在线观看]
     * @author xiezy
     * @date   2018-04-18
     * @return [type]     [description]
     */
    public function showVideoOnline(){
        $where['ordersn'] = I('get.ordersn');

        $result = $this->videoBookInfoModel->where($where)->find();
        $this->assign('info',$result);
        $this->display();
    }

    /**
     * [payForCheckInfo 付款前检测是否完善信息成功]
     * @author xiezy
     * @date   2018-04-18
     * @return [type]     [description]
     */
    public function payForCheckInfo(){
        $where['ordersn'] = I('post.ordersn');
        $where['father_name'] = array('NEQ',NULL);
        $where['father_name'] = array('NEQ','');
        $where['monther_name'] = array('NEQ',NULL);
        $where['monther_name'] = array('NEQ','');

        $result = $this->videoBookInfoModel->where($where)->find();
        // echo '<meta charset="UTF-8"><pre>xie '.date('Y-m-d H:i:s',time()).'</br></br>';var_dump($result);die;
        if($result){
            $info['status'] = 1;
            $info['info'] = '付款';
            // $info['url'] = U(MODULE_NAME.'/personal/my_baby_order');
            $this->ajaxReturn($info);
        }else{
            $info['status'] = 0;
            $info['info'] = '请填写完善信息';
            $this->ajaxReturn($info);
        }
    }

    /**
     * 产生随机字符串，不长于32位
     * @param int $length
     * @return string 产生的随机字符串
     */
    public static function getNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

    /**
     * [wx_config 微信配置-接口]
     * @author xiezy
     * @date   2017-10-18
     * @return [type]     [description]
     */
    private static function wx_config($decode_url){
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $jsapi_ticket            = cookie('jsapi_ticket');  //获取jsapi_ticket
        $configData['appId']     = C('WX_APPID');           //APPID
        $configData['timeStamp'] = time();                  //签名的时间戳
        $configData['nonceStr']  = static::getNonceStr();   //签名的随机串
        $configData['url']       = $decode_url;             //签名的url（需要和当前页面一模一样）
        // $configData['url']       = $url; //签名的url（需要和当前页面一模一样）
        // $configData['url']       = 'https://washcar.zhfancon.com/index/wash_shop_list.html'; //签名的url（需要和当前页面一模一样）
        $ticket = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$configData['nonceStr'].'&timestamp='.$configData['timeStamp'].'&url='.$configData['url'];
        $configData['signature'] = sha1($ticket);           //签名

        return $configData ? $configData : null;
    }

    /**
     * [wx_onMenuShareAppMessage 微信录音-接口]
     * @author xiezy
     * @date   2017-10-18
     * @return [type]     [description]
     */
    public function getWxConfig(){
        $url        = I('post.url');
        $decode_url = urldecode($url);
        /*获取微信配置数据*/
        $data = static::wx_config($decode_url);
        if ( !empty($data) ) {
            $this->ajaxReturn(array('status'=>1,'info'=>'获取成功','data'=>$data));
        }else{
            $this->ajaxReturn(array('status'=>0,'info'=>'获取失敗','data'=>$data));
        }
    }

    //amr转码
    public function amrTomp3($amrPath,$filename,$ordersn){
        //最终转码文件名
        $mp3Name = $filename.".mp3";

        //最终转码目录
        $ordersnDir     = $ordersn.'/'.date("Y-m-d",time());
        $uploadDir      = './Upload/mp3/'.$ordersnDir;

        // 创建目录--最终目录
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir,0777,true);
        }

        //文件转码最终路径
        $uploadPath = $uploadDir ."/". $mp3Name;

        //执行转码操作
        exec("ffmpeg -i {$amrPath} {$uploadPath} ",$out,$int);

        return array("status"=>$int,'path'=>$uploadPath);
    }

    //保存录音
    public function saveRecord(){
        $access_token       = cookie("wx_access_token");    //token
        $record_text        = I("post.record_text");        //语音转文字
        $media_id           = I("post.serverId");           //媒体id
        $where['ordersn']   = I("post.ordersn");            //订单号
        
        
        $checkOrder = $this->videoBookInfoModel->where($where)->find();
        if(I("post.ordersn") == '' || !$checkOrder){
            $data["status"] = 0;
            $data["msg"] = "订单违法！";
            $data['url'] = U(MODULE_NAME.'/'.CONTROLLER_NAME.'/my_baby_order');
            $this->ajaxReturn($data);
        }

        // $path    = "./Upload/wx_record/";   //保存路径，相对当前文件的路径
        $ordersnDir     = $where['ordersn'].'/'.date("Y-m-d",time())."/";
        $path    = "./Upload/wx_record/".$ordersnDir;   //保存路径，相对当前文件的路径

        if(!is_dir($path)){
            mkdir($path,0777,true);
        }

        //获取媒体内容
        $url      = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";
        //最终上传路径
        $filename = "wxrecord_".time().rand(1111,9999);
        $uploadPath = $path.$filename.".amr";
        //根据微信媒体id下载amr文件
        $this->downAndSaveFile($url,$uploadPath);
        //amr转码mp3
        // $res    = $this->amrTomp3($uploadPath,$filename,$where['ordersn']);
        // if ( empty($res['status']) ) {
            //执行成功
            $recordData['record']       = $uploadPath;
            $recordData['record_text']  = iconv('UTF-8','gb2312',$record_text);
            $result                     = $this->videoBookInfoModel->where($where)->save($recordData);

            $data["status"] = 1;
            $data["msg"] = "上传成功";
        // }else{
        //     //执行失败
        //     $data["status"] = 0;
        //     $data["msg"] = "上传失败";
        // }

        // unlink($uploadPath);        //删除amr文件
        $data['url'] = U(MODULE_NAME.'/'.CONTROLLER_NAME.'/compelete_infomation',array('ordersn'=>$where['ordersn'],'type'=>'edit'));
        $this->ajaxReturn($data);
    }

    /**
     * [wx_onMenuShareAppMessage 微信分享给朋友-接口]
     * @author xiezy
     * @date   2017-10-18
     * @return [type]     [description]
     */
    public function wx_onMenuShareAppMessage(){
        $url        = I('post.url');
        $decode_url = urldecode($url);
        /*获取微信配置数据*/
        $data = static::wx_config($decode_url);
        if ($data!=null) {
            $data['title'] = '在线观看'; //分享标题
            $data['desc']  = '我的宝贝视频,分享喜悦瞬间。';   //分享描述
            $data['url']   = $decode_url;    //分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            // $data['url']   = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];    //分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            // $data['url'] = 'https://washcar.zhfancon.com/index/wash_shop_list.html';    //分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            $data['headImgUrl'] = 'http://pic1.wed114.cn/allimg/170816/41_170816101932_2.jpg'; // 分享图标
            $this->ajaxReturn(array('status'=>1,'info'=>'分享成功','data'=>$data));
        }else{
            $this->ajaxReturn(array('status'=>0,'info'=>'分享失敗','data'=>$data));
        }
    }
}
